package com.qijian.maindata.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.SysRole;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.maindata.domain.BomCraftFile;
import com.qijian.maindata.domain.dto.BomStorageDTO;
import com.qijian.maindata.domain.query.BomCraftFileQuery;
import com.qijian.maindata.domain.vo.BomCraftFileVo;
import com.qijian.maindata.domain.vo.BomCraftFilesSendMsgVo;
import com.qijian.maindata.service.IBomCraftFileService;
import com.qijian.tool.domain.Msg;
import com.qijian.tool.service.IMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 【Bom的工艺附件】Controller
 *
 * @author qijian
 * @date 2023-11-15
 */
@Api(tags = "【Bom的工艺附件】")
@RestController
@RequiredArgsConstructor
@RequestMapping("/maindata/bomCraftFile")
public class BomCraftFileController extends BaseController {

    private final IBomCraftFileService bomCraftFileService;
    private final IMsgService msgService;

    /**
     * bom工艺文件查询
     */
//    @PreAuthorize("@ss.hasPermi('business:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(BomCraftFileQuery query, Page<BomCraftFile> page) {
        initOrderItem(BomCraftFile.class, page.orders());
        query.setIsEnable(true);
        return getDataTable(bomCraftFileService.pageVo(page, WhereEntityTool.invoke(query)));
    }


    /**
     * 删除bom工艺文件
     */
//    @PreAuthorize("@ss.hasPermi('business:file:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {

        return toAjax(bomCraftFileService.removeByIds(ids));
    }

    /**
     * bom工艺文件新增
     */
//    @PreAuthorize("@ss.hasPermi('tools:storage:add')")
    @Log(title = "数据存储", businessType = BusinessType.INSERT)
    @PostMapping("replaceBomStorage")
    public AjaxResult addBomStorage(@RequestBody BomStorageDTO dto) {
        bomCraftFileService.bomStorageReplace(dto);
        return AjaxResult.success();
    }

    @ApiOperation(value = "工艺文件抄送")
    @PostMapping("/sendMsg")
    public AjaxResult sendMsg(@RequestBody @Valid BomCraftFilesSendMsgVo vo) {
        List<SysUser> userList = vo.getUserList();
        List<BomCraftFileVo> craftFileVoList = vo.getBomCraftFileList();
        List<Msg> msgList = new ArrayList<>();
        for (BomCraftFileVo craftFileVo : craftFileVoList) {
            for (SysUser user : userList) {
                Msg msg = getMsg(craftFileVo, user.getUserId());
                msgList.add(msg);
            }
        }
        if (CollectionUtils.isNotEmpty(msgList)) {
            msgService.saveBatch(msgList);
        }
        return AjaxResult.success();
    }

    public static Boolean isAdministrator() {
        List<SysRole> roles = SecurityUtils.getRoles();
        for (SysRole role : roles) {
            if (role.getRoleName().contains("系统管理员")) {
                return true;
            }
        }
        return false;
    }

    @NotNull
    private Msg getMsg(BomCraftFileVo craftFileVo, Long userId) {
        // 发送消息
        Msg msg = new Msg();

        msg.setContent(String.format("BOM(%s)工艺文件%s已上传",craftFileVo.getItemCode(),craftFileVo.getRealName()));
        msg.setTitle(String.format("BOM(%s)工艺文件%s已上传",craftFileVo.getItemCode(),craftFileVo.getRealName()));
        msg.setIsClose(false);
        msg.setUserId(userId);
        msg.setIsRead(false);
        msg.setSourceId(String.valueOf(craftFileVo.getId()));
        msg.setSourceType("main_bom_craft_file");
        msg.setUrl("/info_process/bomStorageList?bomId=" + craftFileVo.getBomId());
        return msg;
    }
}
